﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Bestcomy.Web.Controls.Upload;
using System.IO;
public partial class SysYcjy_createuser_auto : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Visible = false;
        //LinkButton1.Visible = false;
        Button2.Enabled = false;
        //if (!IsPostBack)      //该行必须取消，否则第二次调用aspnetupload 控件必然出现网页错误--缺少对象！
        //{
            Session["sTittle"] = "批量建立用户";
            Label1.Visible = false;
            //获取上传文件保存的路径
            string fpath = Path.Combine(Request.PhysicalApplicationPath, "temp");
            if (!Directory.Exists(fpath))
            {
                Directory.CreateDirectory(fpath);
            }
            AspnetUpload upldr = new AspnetUpload();
            upldr.set_UploadFolder(fpath);
            upldr.RegisterModelessProgressBar(this.Button1);
        //}
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //测试文件类型是否符合的变量
        Boolean fileOK = false;
        //设置服务器中保存文件的路径
        String path = Server.MapPath("~/temp/");
        //判断是否选择了文件
        if (FileUpload1.HasFile)
        {
            //返回文件的扩展名
            String fileExtension =
                System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
            //设置限定的文件类型
            String[] allowedExtensions = 
            //{ ".txt", ".doc", ".wmv", "asx",".jpg","xml" ,""swf"};
            { ".txt" };
            //判断用户选择的文件类型是否受限
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }
        }
        //如果文件大于1M，则不允许上传
        if (FileUpload1.PostedFile.ContentLength > 10240000)
        {
            fileOK = false;
        }
        //如果文件类型符合
        if (fileOK)
        {
            try
            {
                // 将文件保存到指定的文件夹下
                //string zfilename = Session["sUserName"].ToString()+".txt";
                //string zfilename = Session["sUserName"].ToString() + System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                string zfilename = Session["sUserName"].ToString() + ".txt";
                FileUpload1.PostedFile.SaveAs(path + zfilename);
                Label1.Visible = true;
                Label1.Text = "文件上传成功，可以批量生成用户了";
                Button2.Enabled = true;

            }
            catch
            {
                Label1.Visible = true;
                ClientScript.RegisterStartupScript(GetType(),"status", "<script>alert('无法实现文件的上传')</script>");
            }
        }
        else
        {
            Label1.Visible = true;
            ClientScript.RegisterStartupScript(GetType(), "status", "<script>alert('本次上传文件未成功。文件类型不对或文件超出10M')</script>");
        }
    }
    protected void FileUpload1_Unload(object sender, EventArgs e)
    {
        Label1.Visible = false;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        //依据系统管理员上传的Session["sUserName"].ToString() + ".txt"文件所指定的用户自动生成远程教育用户。
        //用到的技巧：随机生成密码、文件读、文件写、数组split方法、创建用户方法、用c#命令生成html超链接,。
        //string zfilename = Session["sUserName"].ToString() + System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
        string zfilename = Session["sUserName"].ToString() + ".txt";//读入的文件名
        String zpath = Server.MapPath("~/temp/");
        string zfilename_status = Session["sUserName"].ToString() + ".html";//写入的文件名
        string zstatus = "";    //保存生成用户的状态，操作结束后一次性写入zfilename_status.html供用户查询。
        try
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader(zpath + zfilename, System.Text.Encoding.GetEncoding("gb2312")))  
                //System.Text.Encoding.GetEncoding("gb2312")是为了转换中文，如果没有这个选项，则读出的中文字符为乱码
            {
                String line;
                string zpwd;
                // Read and display lines from the file until the end of 
                // the file is reached.
                int i = 1;
                string[] zuserinfo;
                string zresult = "";
                while ((line = sr.ReadLine()) != null)
                {
                    //Console.WriteLine(line);
                    //拆分每行为用户名、用户中文名、电子邮件
                    zuserinfo=line.Split(',');
                    zpwd = MakePassword(7)+"!";
                    zresult=zcreate_user(zuserinfo[0],zuserinfo[1],zuserinfo[2],zpwd);
                    //zstatus += i.ToString() + "、" + zuserinfo[0] + "(" + zuserinfo[1] + ")生成状态：" + zresult + "<br>";
                    //zstatus+=i.ToString()+"、"+zuserinfo[0]+"("+zuserinfo[1]+",密码：)"+zpwd+"生成状态："+zresult+"\r\n";
                    if(zresult=="操作正确，创建用户成功！")
                        zstatus += i.ToString() + "、" + zuserinfo[0] + "(" + zuserinfo[1] + ",密码：" + zpwd + ")生成状态：成功！<br>";
                    else
                        zstatus += i.ToString() + "、" + zuserinfo[0] + "(" + zuserinfo[1] + ")生成状态：" + zresult + "<br>";
                    i += 1;

                }
            }
        }
        //catch (Exception e)
        catch
        {
            // Let the user know what went wrong.
            //Console.WriteLine("The file could not be read:");
            //Console.WriteLine(e.Message);
            zstatus+="The file could not be read.";
        }

        //写入结果文件
        
        
        
        //string zpath = Request.PhysicalApplicationPath + "temp" + Path.DirectorySeparatorChar;//已经定义了zpath
        create_file(zpath,zfilename_status,zstatus);
        
        
        //指向生成结果html文件的连接
        //Response.Write("<hr>生成完毕。用户状态保存于：<a   href='~/temp/" + zfilename_status + "'   target='_blank'>打开</a> ");
        //LinkButton1.PostBackUrl = "~/temp/" + zfilename_status;
        //LinkButton1.Visible = true;
        HyperLink14.NavigateUrl = "~/temp/" + zfilename_status;
        HyperLink14.Enabled = true;
        Button3.Enabled = true;
        //Response.Write("<script language=javascript>alert('操作正确,批量增加用户完成，具体完成状态请查看状态文件。');if(opener!=null){opener.location.reload();window.close();}</script>");
        //opener.location 为空或不是对象
        Label1.Visible = true;
        Label1.Text = "操作正确,批量增加用户完成，具体完成状态请查看状态文件。";
    }
    protected string zcreate_user(string zusername, string zusername1, string zmail, string zpwd)
    {
        //初始化必要参数
        
        string zrole = "学员";
        string zcreateman = Session["sUserName1"].ToString();
        string zxtsj1 = DateTime.Now.ToString();
        string zq1 = "您使用的远教平台是什么?";
        string zq2 = "www.zxuexi.net";
        string zjigou = DropDownList2.SelectedValue.ToString();

        //zsql = "insert into [account] (role,username,mail,username1,gzdw,city,mobile,email,grjj,jigou,createman,xtsj1) values ('学员','" + zusername + "','" + zmail + "','" + zusername1 + "','" + zgzdw + "','" + zcity + "','" + zmobile + "','" + zemail1 + "','" + zgrjj + "','" + zjigou + "','" + zcreateman + "','" + zxtsj1 + "')";
        string zsql = "insert into [account] (role,username,mail,username1,jigou,createman,xtsj1,grjj) values ('学员','" + zusername + "','" + zmail + "','" + zusername1  + "','" + zjigou + "','" + zcreateman + "','" + zxtsj1 + "','家园互动批量用户')";
        //以上搜集必要数据

        //以下开始新建用户
        MembershipCreateStatus result;
        Membership.CreateUser(zusername, zpwd, zmail, zq1, zq2, true, out result);
        string zresult = "";
        switch (result)
        {
            case MembershipCreateStatus.Success:    //添加系统数据成功，可以添加角色和用户表account

                //以下添加account表

                //以下判断是否添加成功，若不成功，彻底删除该用户，并提示。
                Conn conn = new Conn();
                if (conn.ExeSql(zsql) == 1) //若成功，则添加角色，否则提示出错，并删除系统表中该用户。
                {
                    Roles.AddUserToRole(zusername, zrole);  //添加角色,注意该方法不返回任何值，只要输入2个string变量即可通过！即直接向系统表添加。
                    conn.Dispose();
                    zresult="操作正确，创建用户成功！";
                    //Response.Redirect("../index.aspx");//在框架中此命令不能返回到父框架。尝试用其他方式如下：
                    //Response.Write(" <script> top.location.href='../index.aspx'; </script> ");
                    //Response.Redirect("createuserwizard.aspx"); //如果用这个命令，则提示信息用户看不到。
                    //Response.Write(" <script> location.href='../index.aspx'; </script> ");

                }//直接执行，暂时不考虑失败情况
                else   //若向用户表中添加用户失败，则删除系统表中的对应数据，相当于没有作任何操作。
                {
                    conn.Dispose();
                    Membership.DeleteUser(zusername, true);
                    zresult = "失败--建立用户表失败。";
                }
                break;

            case MembershipCreateStatus.InvalidUserName:
                zresult = "失败--非法的用户名。";
                break;
            case MembershipCreateStatus.InvalidPassword:
                zresult = "失败--密码不符合规范，必须7位数以上，且必须包含至少1位非字母非数字字符，如“~！·#￥%……—*”。";
                break;

            case MembershipCreateStatus.InvalidEmail:
                zresult = "失败--不符合要求的电子邮件信箱，请重新输入。";
                break;
            case MembershipCreateStatus.InvalidQuestion:
                zresult = "失败--安全问题不符合要求，请重新输入。";
                break;
            case MembershipCreateStatus.InvalidAnswer:
                zresult = "失败--安全问题回答不符合要求，请重新输入。";
                break;
            case MembershipCreateStatus.DuplicateUserName:
                zresult = "失败--用户名重复，请重新选择用户名。";
                break;
            case MembershipCreateStatus.DuplicateEmail:
                zresult = "失败--用户信箱重复。";
                break;
            default:
                zresult = "失败--创建用户时出现了不可预知的错误。";
                break;
        }
        return zresult;
    }
    private static string MakePassword(int pwdLength) 
  { 
   //声明要返回的字符串 
   string tmpstr = ""; 
   //密码中包含的字符数组 
   string pwdchars="abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVW!$%"; 
   //数组索引随机数 
   int iRandNum; 
   //随机数生成器 
   Random rnd = new Random(); 
   for(int i=0;i<pwdLength;i++) 
   { 
    //Random类的Next方法生成一个指定范围的随机数 
    iRandNum = rnd.Next(pwdchars.Length); 
    //tmpstr随机添加一个字符 
    tmpstr += pwdchars[iRandNum]; 
   } 
   return tmpstr; 
  }


    protected void DropDownList2_DataBound(object sender, EventArgs e)
    {
        if (DropDownList2.Items.Count > 0)
        {
            DropDownList2.SelectedIndex = 0;
        }
        else
        {
            SqlDataSource3.SelectCommand = "select * from account where 1=2";
            Button1.Enabled = false;
            Button2.Enabled = false;
            Label1.Visible = true;
            Label1.Text = "因为没有合适的机构数据,因此目前该功能不可用.请联络系统管理员";
        }
        Label1.Visible = false;
        //LinkButton1.Visible = false;
        Button2.Enabled = false;
    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Visible = false;
        //LinkButton1.Visible = false;
        Button2.Enabled = false;
    }
    public void create_file(string pathname, string filename, string filecontent)
    {
        DirectoryInfo di = new DirectoryInfo(pathname);
        di.Create();

        string fileurl = pathname + filename;

        FileInfo fi = new FileInfo(fileurl);
        //也可以用FileStream fs = new FileStream(FileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
        //其中不用CreateNew，而是用Create，因为前者当文件已经存在时会提示出错，而后者这时先删除文件，然后新建一个
        //最后简化为：FileStream fs = new FileStream(FileName, FileMode.Create);
        //参见http://www.cnblogs.com/yank/archive/2007/11/16/961878.html
        var sw = new System.IO.StreamWriter(fileurl, false, System.Text.Encoding.Default);
        sw.WriteLine(filecontent);
        sw.Flush();
        sw.Close();



    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        //删除状态文件：批量添加用户等操作完成后，请务必及时删除状态文件（操作人用户名.html），以避免造成密码泄露隐患。
        //删除完毕后即不允许查看状态文件了
        

        String zpath = Server.MapPath("~/temp/");
        string zfilename = zpath+Session["sUserName"].ToString() + ".txt";//读入的文件名
        
        string zfilename_status = zpath+Session["sUserName"].ToString() + ".html";//写入的文件名

        if (File.Exists(zfilename))
            File.Delete(zfilename);

        if(File.Exists(zfilename_status))
            File.Delete(zfilename_status);
        //Response.Write("<script language=javascript>alert('相关状态文件删除成功！！');if(opener!=null){opener.location.reload();window.close();}</script>");
        //opener.location 为空或不是对象
        Label1.Visible = true;
        Label1.Text = "相关状态文件删除成功！！";
        
        HyperLink14.Enabled = false;
    }
}
